import { ProFormSelect, StatisticCard, ProCard } from '@ant-design/pro-components';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
// import { Divider } from 'antd';
import { useState } from 'react';
import { Pie, Column } from '@ant-design/plots';
import { queryParkinglotNames } from '../Parking/Spot/service';
import type { HourDataType, LotDailyStatisticType } from './types.d';
import { getDailyStatistic } from './service';
import { Button, message, Progress } from 'antd';
import { FullscreenExitOutlined, FullscreenOutlined, ReloadOutlined } from '@ant-design/icons';
import { HOURSDEFAULT } from './constants';
import OrderRates from './components/OrderRates';
const DEFAULT_DAILY: LotDailyStatisticType = {
  actualAmount: 0,
  payableAmount: 0,
  totalOrder: 0,
  freeOrder: 0,
  chargedOrder: 0,
  parkingTraffic: 0,
  parkingLotId: '',
  ownerId: 'admin',
  parkingLotName: '无效路段',
  spotCount: 0,
  hours: [],
  createTime: new Date('2022-01-01'),
  omissiveOrder: 0,
  printedOrder: 0,
  recoveryOrder: 0,
  occupySpots: 0,
};
const translateFentoYuan = (amount: number) => {
  if (!amount || amount < 0) return 0;
  const result = parseFloat((amount / 100).toFixed(2));
  return Number.isNaN(result) ? 0 : result;
};
const handleHoursData = (hours: HourDataType[] = []) => {
  if (hours.length > 0) {
    const res: { type: string; value: number; hours: string }[] = [];
    hours
      .sort((a, b) => a?.recordHour - b?.recordHour)
      .forEach((item) => {
        res.push(
          {
            type: '应收',
            value: translateFentoYuan(item.payableAmount),
            hours: `${item.recordHour}时`,
          },
          {
            type: '实收',
            value: translateFentoYuan(item.actualAmount),
            hours: `${item.recordHour}时`,
          },
        );
      });
    return res;
  } else return HOURSDEFAULT;
};
export default () => {
  const [currDaily, setCurrDaily] = useState<LotDailyStatisticType>(DEFAULT_DAILY);
  const [currParkingLotId, setCurrParkingLotId] = useState<string>('');
  const [isFullScreen, setIsFullScreen] = useState<boolean>(false);
  return (
    <PageHeaderWrapper
      className="homepage"
      header={{
        title: '',
        breadcrumb: undefined,
      }}
    >
      <ProCard
        id="dashboard"
        direction="column"
        split="horizontal"
        title={
          <ProFormSelect
            className="YYHIOHHI"
            showSearch={true}
            fieldProps={{
              style: {
                width: '210px',
              },
              onChange: (val: string) => {
                setCurrParkingLotId(val || '');
                if (val) {
                  getDailyStatistic(val).then((res) => {
                    if (res.success) {
                      setCurrDaily(res.data || DEFAULT_DAILY);
                    } else {
                      message.error({
                        content: res?.message || '获取失败',
                        key: 'getDailyStatistic',
                      });
                      setCurrDaily(DEFAULT_DAILY);
                    }
                  });
                }
              },
            }}
            debounceTime={300}
            request={(val) => queryParkinglotNames(val?.keyWords || '')}
            width="xl"
            label="路段名称"
          />
        }
        extra={
          <>
            <Button
              title="刷新"
              type="link"
              onClick={() => {
                if (currParkingLotId) {
                  getDailyStatistic(currParkingLotId).then((res) => {
                    if (res.success) {
                      setCurrDaily(res.data || DEFAULT_DAILY);
                    } else {
                      message.error({
                        content: res?.message || '获取失败',
                        key: 'getDailyStatistic',
                      });
                      setCurrDaily(DEFAULT_DAILY);
                    }
                  });
                }
              }}
            >
              <ReloadOutlined />
            </Button>
            <Button
              title="全屏"
              type="link"
              onClick={() => {
                const dom = document.getElementById('dashboard');
                if (dom && !isFullScreen) {
                  if (dom.requestFullscreen) {
                    dom.requestFullscreen();
                    // @ts-ignore
                  } else if (dom.webkitRequestFullScreen) {
                    // @ts-ignore
                    dom.webkitRequestFullScreen();
                    // @ts-ignore
                  } else if (dom.mozRequestFullScreen) {
                    // @ts-ignore
                    dom.mozRequestFullScreen();
                    // @ts-ignore
                  } else if (dom.msRequestFullscreen) {
                    // @ts-ignore
                    dom.msRequestFullscreen();
                  } else {
                    message.warn({
                      content:
                        '当前浏览器不支持全屏浏览，请尝试以下浏览器中的某一个：Chrome、Firefox、Safari',
                      key: 'no-fullscreen',
                    });
                  }
                } else if (document.exitFullscreen) {
                  document.exitFullscreen();
                  // @ts-ignore
                } else if (document.webkitExitFullscreen) {
                  // @ts-ignore
                  document.webkitExitFullscreen();
                  // @ts-ignore
                } else if (document.mozCancelFullScreen) {
                  // @ts-ignore
                  document.mozCancelFullScreen();
                  // @ts-ignore
                } else if (document.msExitFullscreen) {
                  // @ts-ignore
                  document.msExitFullscreen();
                } else {
                  message.warn({
                    content: '如果无法点击退出全屏，请尝试点击键盘Esc键',
                    key: 'no-fullscreen',
                  });
                }
                setIsFullScreen(!isFullScreen);
              }}
            >
              {isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
            </Button>
          </>
        }
      >
        <StatisticCard.Group
          bordered
          title={<span style={{ fontSize: '20px', fontWeight: 'bold' }}>路段信息</span>}
          split="vertical"
        >
          <StatisticCard statistic={{ title: '路段名称', value: currDaily.parkingLotName }} />
          <StatisticCard
            statistic={{
              title: '泊位总数',
              value: currDaily.spotCount,
              precision: 0,
              suffix: '个',
            }}
          />
          <StatisticCard
            statistic={{
              title: '停车流量',
              value: currDaily.parkingTraffic,
              precision: 0,
              suffix: '辆',
            }}
          />
          <StatisticCard
            statistic={{
              title: '追缴欠费',
              value: currDaily.recoveryOrder,
              precision: 0,
              suffix: '单',
            }}
          />
        </StatisticCard.Group>
        <ProCard
          bordered
          title={
            <span style={{ fontSize: '20px', fontWeight: 'bold', color: '#888' }}>统计数据</span>
          }
          split="vertical"
        >
          <ProCard colSpan="65%" style={{ minHeight: '65vh' }}>
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                width: '100%',
                height: '100%',
                textAlign: 'center',
              }}
            >
              <p style={{ fontSize: '20px' }}>日营收额度统计</p>
              <div style={{ flex: 1 }}>
                <Column
                  style={{
                    height: '60vh',
                    width: '100%',
                  }}
                  xField="hours"
                  yField="value"
                  isGroup={true}
                  seriesField={'type'}
                  autoFit={true}
                  legend={{
                    layout: 'horizontal',
                    position: 'top-left',
                    itemName: {
                      style: () => ({
                        fontSize: 16,
                      }),
                    },
                  }}
                  minColumnWidth={30}
                  dodgePadding={0}
                  scrollbar={{
                    type: 'horizontal',
                  }}
                  label={{
                    position: 'middle',
                    style: {
                      fill: '#FFFFFF',
                      opacity: 0.8,
                      fontSize: 12,
                    },
                  }}
                  xAxis={{
                    label: {
                      style: {
                        fontSize: 16,
                      },
                    },
                  }}
                  yAxis={{
                    label: {
                      style: {
                        fontSize: 16,
                      },
                    },
                    title: { text: '金额/元', position: 'end' },
                  }}
                  // data={[
                  //   { type: '应收', value: translateFentoYuan(currDaily.payableAmount) },
                  //   { type: '实收', value: translateFentoYuan(currDaily.actualAmount) },
                  // ]}
                  data={handleHoursData(currDaily.hours)}
                  meta={{
                    type: {
                      alias: '类别',
                    },
                    value: {
                      alias: '金额(元)',
                    },
                  }}
                />
              </div>
            </div>
          </ProCard>
          <ProCard colSpan="35%" style={{ height: '100%' }}>
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'space-between',
                width: '100%',
                height: '100%',
                textAlign: 'center',
              }}
            >
              <p style={{ textAlign: 'left', display: 'flex', alignItems: 'center' }}>
                <span style={{ margin: '0 5px 0 20px', fontSize: '16px' }}>泊位占用率：</span>
                <Progress
                  strokeColor="red"
                  percent={Number(((currDaily.occupySpots / currDaily.spotCount) * 100).toFixed(2))}
                  steps={60}
                  strokeWidth={16}
                  size="small"
                />
              </p>
              <p style={{ fontSize: '20px' }}>日订单统计</p>
              <div>
                <Pie
                  style={{
                    height: '30vh',
                    width: '100%',
                  }}
                  data={[
                    { type: '收费订单', value: currDaily.chargedOrder },
                    { type: '免费订单', value: currDaily.freeOrder },
                    {
                      type: '在停订单',
                      value: currDaily.totalOrder - (currDaily.chargedOrder + currDaily.freeOrder),
                    },
                  ]}
                  angleField="value"
                  colorField="type"
                  appendPadding={2}
                  statistic={{
                    title: {
                      content: '全部订单',
                      style: {
                        fontSize: '18px',
                      },
                    },
                  }}
                  label={{
                    type: 'inner',
                    style: {
                      fontSize: 18,
                    },
                  }}
                  legend={{
                    title: {
                      text: '',
                    },
                    itemName: {
                      style: () => ({
                        fontSize: 16,
                      }),
                    },
                  }}
                  radius={0.8}
                  innerRadius={0.65}
                />
              </div>
              <div
                style={{
                  flex: 1,
                }}
              >
                <OrderRates
                  total={currDaily.totalOrder}
                  omissive={currDaily.omissiveOrder}
                  free={currDaily.freeOrder}
                  printed={currDaily.printedOrder}
                />
              </div>
            </div>
          </ProCard>
        </ProCard>
      </ProCard>
    </PageHeaderWrapper>
  );
};
